package com.thprojects.myphotomemories.controller;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class FacebookController {
	Facebook mFacebook;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;
    Activity mActivity;
    String[] mPermissions;
    AsyncFacebookRunner mAsyncRunner;
    
    public FacebookController(String appId, Activity activity, String[] permissions){
    	mFacebook = new Facebook(appId);
    	mActivity = activity;
    	mPermissions = permissions;
    	mAsyncRunner = new AsyncFacebookRunner(mFacebook);
    	/*
         * Get existing access_token if any
         */
        mPrefs = mActivity.getPreferences(Context.MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        if(access_token != null) {
        	mFacebook.setAccessToken(access_token);
        }
        if(expires != 0) {
        	mFacebook.setAccessExpires(expires);
        }
        
        login();
        
    }
    
    public void login(){
    	/*
         * Only call authorize if the access_token has expired.
         */
        if(!mFacebook.isSessionValid()) {

        	mFacebook.authorize(mActivity, mPermissions, new DialogListener() {
                public void onComplete(Bundle values) {
                    SharedPreferences.Editor editor = mPrefs.edit();
                    editor.putString("access_token", mFacebook.getAccessToken());
                    editor.putLong("access_expires", mFacebook.getAccessExpires());
                    editor.commit();
                }
    
                public void onFacebookError(FacebookError error) {}
    
                public void onError(DialogError e) {}
    
                public void onCancel() {}
            });
        }
    }
    
    public void logout(){
    	mAsyncRunner.logout(mActivity, new RequestListener() {
    		  public void onComplete(String response, Object state) {}
    		  
    		  public void onIOException(IOException e, Object state) {}
    		  
    		  public void onFileNotFoundException(FileNotFoundException e,
    		        Object state) {}
    		  
    		  public void onMalformedURLException(MalformedURLException e,
    		        Object state) {}
    		  
    		  public void onFacebookError(FacebookError e, Object state) {}
    		});
    }
    
    
    public void postPhotoOnWall(String msg, Bitmap photo, RequestListener rl){
    	Bundle params = new Bundle();

        params.putByteArray("photo", bitmapToByteArray(photo));

        params.putString("caption", msg);
        mAsyncRunner.request("me/photos", params, "POST", rl, null);
    }

    
    public static Bitmap byteArrayToBitmap(byte[] blob){
		Bitmap bmp = BitmapFactory.decodeByteArray(blob,0,blob.length);
		return bmp;
	}
	
	public static byte[] bitmapToByteArray(Bitmap bm){
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(CompressFormat.PNG, 100, stream);
		return stream.toByteArray();
	}

	public static Bitmap intArrayToBitmap(int[] pixels, int width, int height) {
		Bitmap res = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		res.setPixels(pixels, 0, width, 0, 0, width, height);
		
		return res;
	}

}
